package com.yuma.tingshu;

import com.yuma.tingshu.album.client.AlbumInfoFeignClient;
import com.yuma.tingshu.album.client.CategoryFeignClient;
import com.yuma.tingshu.common.result.Result;
import com.yuma.tingshu.common.util.PinYinUtils;
import com.yuma.tingshu.model.album.AlbumAttributeValue;
import com.yuma.tingshu.model.album.BaseCategoryView;
import com.yuma.tingshu.model.search.AlbumInfoIndex;
import com.yuma.tingshu.model.search.AttributeValueIndex;
import com.yuma.tingshu.model.search.SuggestIndex;
import com.yuma.tingshu.model.user.UserInfo;
import com.yuma.tingshu.user.client.UserInfoFeignClient;
import com.yuma.tingshu.vo.album.AlbumListVo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@SpringBootTest
public class ServiceSearchApplicationTest2 {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Test
    public void importData() {

        // 创建索引和映射
        IndexOperations indexOps = elasticsearchTemplate.indexOps(AlbumInfoIndex.class);
        if(!indexOps.exists()){
            indexOps.createWithMapping();
        }

        // 创建提示词库索引和映射
        IndexOperations suggestOps = elasticsearchTemplate.indexOps(SuggestIndex.class);
        if (!suggestOps.exists()){
            suggestOps.create();
            suggestOps.putMapping();
        }

        Integer pageNum = 1;
        Integer pageSize = 100;

        do {
            // 导入数据
            //1.分页查询100条专辑数据,对每一条数据构建索引
            Result<List<AlbumListVo>> result = albumInfoFeignClient.findAlbumPage(pageNum, pageSize);
            List<AlbumListVo> albumListVos = result.getData();
            Assert.notNull(albumListVos,"导入数据时，查询专辑列表信息为空");
            if (CollectionUtils.isEmpty(albumListVos)){ // 如果该页数据为空，说明可能是最后一页了，则直接结束
                return;
            }
            albumListVos.forEach(albumListVo -> {
                AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
                BeanUtils.copyProperties(albumListVo,albumInfoIndex);
                albumInfoIndex.setId(albumListVo.getAlbumId());//名称不一致，需要手动设置

                //2.获取3个分类名称信息
                Result<BaseCategoryView> baseCategoryViewResult = categoryFeignClient.getBaseCategoryViewByCategory3Id(albumListVo.getCategory3Id());
                BaseCategoryView baseCategoryView = baseCategoryViewResult.getData();
                if (baseCategoryView != null){
                    albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
                    albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
                }
                //3.获取主播名称
                Result<UserInfo> userInfoResult = userInfoFeignClient.getUserById(albumListVo.getUserId());
                UserInfo userInfo = userInfoResult.getData();
                Assert.notNull(userInfoResult, "数据导入时，获取主播信息失败！" + albumListVo.getUserId());
                if (userInfo != null){
                    albumInfoIndex.setAnnouncerName(userInfo.getNickname());
                }

                //4.获取专辑统计信息
                albumInfoIndex.setPlayStatNum(ThreadLocalRandom.current().nextInt(10000)+10000);
                albumInfoIndex.setSubscribeStatNum(ThreadLocalRandom.current().nextInt(10000)+10000);
                albumInfoIndex.setBuyStatNum(ThreadLocalRandom.current().nextInt(10000)+10000);
                albumInfoIndex.setCommentStatNum(ThreadLocalRandom.current().nextInt(10000)+10000);
                albumInfoIndex.setHotScore(albumInfoIndex.getPlayStatNum()*0.2 + albumInfoIndex.getCommentStatNum()*0.2
                        +albumInfoIndex.getBuyStatNum()*0.3+albumInfoIndex.getSubscribeStatNum()*0.3);

                //5.获取专辑标签信息
                Result<List<AlbumAttributeValue>> albumAttributeValuesByAlbumId = albumInfoFeignClient.findAlbumAttributeValuesByAlbumId(albumListVo.getAlbumId());
                Assert.notNull(albumAttributeValuesByAlbumId, "数据导入时，获取专辑标签值失败！");
                List<AlbumAttributeValue> albumAttributeValues = albumAttributeValuesByAlbumId.getData();
                if (!CollectionUtils.isEmpty(albumAttributeValues)) {
                    // 把AlbumAttributeValue集合转化成AttributeValueIndex集合
                    List<AttributeValueIndex> attributeValueIndexList = albumAttributeValues.stream().map(albumAttributeValue -> {
                        AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                        BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                        return attributeValueIndex;
                    }).collect(Collectors.toList());
                    albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);
                }

                this.elasticsearchTemplate.save(albumInfoIndex);

                /// 保存数据到提示词库
                // 标题
                SuggestIndex titleSuggestIndex = new SuggestIndex();
                titleSuggestIndex.setId("title_" + albumListVo.getAlbumId()); // 需要指定id，以方便将来实时同步数据。
                titleSuggestIndex.setTitle(albumListVo.getAlbumTitle());
                titleSuggestIndex.setKeyword(new Completion(List.of(albumListVo.getAlbumTitle())));
                titleSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(albumListVo.getAlbumTitle()))));
                titleSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.getFirstLetter(albumListVo.getAlbumTitle()))));
                elasticsearchTemplate.save(titleSuggestIndex);
                // 简介
                SuggestIndex introSuggestIndex = new SuggestIndex();
                introSuggestIndex.setId("intro_" + albumListVo.getAlbumId()); // 需要指定id，以方便将来实时同步数据。
                introSuggestIndex.setTitle(albumListVo.getAlbumIntro());
                introSuggestIndex.setKeyword(new Completion(List.of(albumListVo.getAlbumIntro())));
                introSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(albumListVo.getAlbumIntro()))));
                introSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.getFirstLetter(albumListVo.getAlbumIntro()))));
                elasticsearchTemplate.save(introSuggestIndex);
                // 主播
                if (userInfo != null){
                    SuggestIndex announceSuggestIndex = new SuggestIndex();
                    announceSuggestIndex.setId("announce_" + userInfo.getId()); // 需要指定id，以方便将来实时同步数据。
                    announceSuggestIndex.setTitle(userInfo.getNickname());
                    announceSuggestIndex.setKeyword(new Completion(List.of(userInfo.getNickname())));
                    announceSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(userInfo.getNickname()))));
                    announceSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.getFirstLetter(userInfo.getNickname()))));
                    elasticsearchTemplate.save(announceSuggestIndex);
                }

            });
            System.out.println(pageNum+"  page do!!!");
            pageNum++;
            pageSize = albumListVos.size();
        } while (pageSize == 100);
    }
}
